<template>
  <div class="app-container">
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      size="small"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="指派人" prop="assigner">
        <el-select
          clearable
          filterable
          v-model="queryParams.assigner"
          placeholder="请选择指派人"
        >
          <el-option
            v-for="item in memberOptions"
            :key="item.memberId"
            :label="item.memberName"
            :value="item.memberId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出车人" prop="driver">
        <el-select
          filterable
          v-model="queryParams.driver"
          clearable
          placeholder="请选择出车人"
        >
          <el-option
            v-for="item in memberOptions"
            :key="item.memberId"
            :label="item.memberName"
            :value="item.memberId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="起点" prop="departureLocation">
        <el-input
          v-model="queryParams.departureLocation"
          placeholder="请输入起点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目的地" prop="destination">
        <el-input
          v-model="queryParams.destination"
          placeholder="请输入目的地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发车时间">
        <el-date-picker
          v-model="dateRangeStartTime"
          size="small"
          style="width: 220px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="dateRangeEndTime"
          size="small"
          style="width: 220px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结账状态" prop="settleStatus">
        <el-select
          v-model="queryParams.settleStatus"
          placeholder="结账状态"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dict in dict.type.trip_settle_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['trip:dailyRecord:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['trip:dailyRecord:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['trip:dailyRecord:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          :disabled="single"
          @click="handleDelegate"
          v-hasPermi="['trip:dailyRecord:delegate']"
          >委派
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          :disabled="multiple"
          @click="handleSettle"
          v-hasPermi="['trip:dailyRecord:edit']"
          >结账
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      border
      stripe
      v-loading="loading"
      :data="dailyRecordList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="行程编号" align="center" prop="tripId" v-if="true"/> -->
      <el-table-column
        label="指派人"
        align="center"
        prop="assignerName"
        width="70"
      />
      <el-table-column
        label="出车人"
        align="center"
        prop="driverName"
        width="70"
      />
      <el-table-column label="起点" align="center" prop="departureLocation" />
      <el-table-column label="目的地" align="center" prop="destination" />
      <el-table-column label="发车时间" align="center" prop="startTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime,'{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="费用（元）" align="center" prop="fare" />
      <el-table-column prop="settleStatus" label="结账状态" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.trip_settle_status"
            :value="scope.row.settleStatus"
          />
        </template>
      </el-table-column>
      <el-table-column prop="delegateStatus" label="委派状态" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.trip_delegate_status"
            :value="scope.row.delegateStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="结账人" align="center" prop="settledBy" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            v-show="scope.row.settleStatus == '0'"
            @click="handleSettle(scope.row)"
            v-hasPermi="['trip:dailyRecord:edit']"
            >结账
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['trip:dailyRecord:edit']"
            >修改
          </el-button>
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['trip:dailyRecord:query', 'trip:dailyRecord:remove']"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >更多</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="
                  scope.row.delegateStatus === '1' ||
                  scope.row.delegateStatus === '2'
                "
                command="handleDetail"
                :icon="
                  scope.row.delegateStatus === '1'
                    ? 'el-icon-share'
                    : 'el-icon-info'
                "
                v-hasPermi="['trip:dailyRecord:query']"
              >
                {{
                  scope.row.delegateStatus === "1"
                    ? "查看委派行程"
                    : "查看原始行程"
                }}
              </el-dropdown-item>
              <el-dropdown-item
                command="handleDelete"
                icon="el-icon-delete"
                v-hasPermi="['trip:dailyRecord:remove']"
                >删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改行程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12">
            <el-form-item label="指派人" prop="assigner">
              <el-select
                style="width: 100%"
                filterable
                v-model="form.assigner"
                clearable
                placeholder="请选择指派人"
              >
                <el-option
                  v-for="item in memberOptions"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId"
                  @keyup.enter.native="handleQuery"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="出车人" prop="driver">
              <el-select
                style="width: 100%"
                filterable
                v-model="form.driver"
                clearable
                placeholder="请选择出车人"
              >
                <el-option
                  v-for="item in memberOptions"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId"
                  @keyup.enter.native="handleQuery"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :xs="24" :sm="12">
            <el-form-item label="起点" prop="departureLocation">
              <el-input
                style="width: 100%"
                clearable
                v-model="form.departureLocation"
                placeholder="请输入起点"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="目的地" prop="destination">
              <el-input
                style="width: 100%"
                clearable
                v-model="form.destination"
                placeholder="请输入目的地"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :xs="24" :sm="12">
            <el-form-item label="发车时间" prop="startTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择发车时间"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :xs="24" :sm="8">
            <el-form-item label="天数" prop="days">
              <el-input-number
                disabled
                style="width: 100%"
                :precision="1"
                controls-position="right"
                :min="0"
                clearable
                v-model="form.days"
                placeholder="自动生成"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="8">
            <el-form-item label="行驶里程(km)" prop="mileage">
              <el-input-number
                style="width: 100%"
                :precision="1"
                controls-position="right"
                :min="1"
                clearable
                v-model="form.mileage"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="8">
            <el-form-item label="费用" prop="fare">
              <el-input-number
                style="width: 100%"
                :precision="2"
                controls-position="right"
                :min="1"
                clearable
                v-model="form.fare"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :xs="24" :sm="12">
            <el-form-item label="结账状态" prop="settleStatus">
              <el-radio-group
                v-model="form.settleStatus"
                :disabled="form.settleStatus == '1'"
              >
                <el-radio-button
                  v-for="dict in dict.type.trip_settle_status"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="结账人" prop="settledBy">
              <el-input
                clearable
                v-model="form.settledBy"
                placeholder="请输入结账人"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                clearable
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 委派行程对话框 -->
    <el-dialog
      title="委派行程"
      :visible.sync="delegateOpen"
      width="800px"
      append-to-body
    >
      <el-form
        ref="delegateForm"
        :model="delegateForm"
        :rules="rules"
        label-width="110px"
      >
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12">
            <el-form-item label="指派人" prop="assigner">
              <el-select
                style="width: 100%"
                filterable
                v-model="delegateForm.assigner"
                clearable
                disabled
                placeholder="请选择指派人"
              >
                <el-option
                  v-for="item in memberOptions"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId"
                  @keyup.enter.native="handleQuery"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="出车人" prop="driver">
              <el-select
                style="width: 100%"
                filterable
                v-model="delegateForm.driver"
                clearable
                placeholder="请选择出车人"
              >
                <el-option
                  v-for="item in memberOptions"
                  :key="item.memberId"
                  :label="item.memberName"
                  :value="item.memberId"
                  @keyup.enter.native="handleQuery"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="8">
            <el-form-item label="费用" prop="fare">
              <el-input-number
                style="width: 100%"
                :precision="2"
                controls-position="right"
                :min="1"
                clearable
                v-model="delegateForm.fare"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12">
            <el-form-item label="结账状态" prop="settleStatus">
              <el-radio-group v-model="delegateForm.settleStatus">
                <el-radio-button
                  v-for="dict in dict.type.trip_settle_status"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12">
            <el-form-item label="结账人" prop="settledBy">
              <el-input
                clearable
                v-model="delegateForm.settledBy"
                placeholder="请输入结账人"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                clearable
                v-model="delegateForm.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="delegateButtonLoading"
          type="primary"
          @click="submitDelegateForm"
          >确 定</el-button
        >
        <el-button @click="cancelDelegateForm">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailOpen"
      width="800px"
      append-to-body
    >
      <el-descriptions
        class="margin-top"
        :column="3"
        border
        v-loading="detailLoading"
      >
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            指派人
          </template>
          {{ detail.assignerName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            出车人
          </template>
          {{ detail.driverName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            起点
          </template>
          {{ detail.departureLocation }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            目的地
          </template>
          {{ detail.destination }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            发车时间
          </template>
          {{ parseTime(detail.startTime, "{y}-{m}-{d}") }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            结束时间
          </template>
          {{ parseTime(detail.endTime, "{y}-{m}-{d}") }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            费用（元）
          </template>
          {{ detail.fare }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            结账状态
          </template>
          <dict-tag
            :options="dict.type.trip_settle_status"
            :value="detail.settleStatus"
          />
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            委派状态
          </template>
          <dict-tag
            :options="dict.type.trip_delegate_status"
            :value="detail.delegateStatus"
          />
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets"></i>
            结账人
          </template>
          {{ detail.settleBy }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets"></i>
            备注
          </template>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDailyRecord,
  getDailyRecord,
  delDailyRecord,
  addDailyRecord,
  updateDailyRecord,
  settleDailyRecord,
  delegateTripRecord,
  queryDelegateInfo,
  queryOriginalInfo,
} from "@/api/trip/dailyRecord";
import { listAllMembers } from "@/api/trip/member";

export default {
  name: "DailyRecord",
  dicts: ["trip_settle_status", "trip_delegate_status"],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      delegateButtonLoading: false,
      // 遮罩层
      loading: true,
      // 遮罩层
      detailLoading: true,
      // 选中数组
      ids: [],
      assigners: [],
      drivers: [],
      totalFare: 0,
      detailTitle: "",
      detailOpen: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行程表格数据
      dailyRecordList: [],
      //发车时间范围
      dateRangeStartTime: [],
      //结束时间范围
      dateRangeEndTime: [],
      //成员列表
      memberOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示委派弹出层
      delegateOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assigner: undefined,
        driver: undefined,
        departureLocation: undefined,
        destination: undefined,
        mileage: undefined,
        startTime: undefined,
        endTime: undefined,
        fare: undefined,
        settleStatus: undefined,
        settledBy: undefined,
      },
      // 表单参数
      form: {},
      delegateForm: {},
      detail: {},
      // 表单校验
      rules: {
        tripId: [
          { required: true, message: "行程ID不能为空", trigger: "blur" },
        ],
        driver: [
          { required: true, message: "出车人不能为空", trigger: "blur" },
        ],
        departureLocation: [
          { required: true, message: "起点不能为空", trigger: "blur" },
        ],
        destination: [
          { required: true, message: "目的地不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "发车时间不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
          { validator: this.checkStartTimeIsAfterEndTime, trigger: "blur" },
        ],
        fare: [{ required: true, message: "费用不能为空", trigger: "blur" }],
        settleStatus: [
          { required: true, message: "结账状态不能为空", trigger: "blur" },
        ],
      },
      delegateRules: {
        driver: [
          { required: true, message: "出车人不能为空", trigger: "blur" },
        ],

        fare: [{ required: true, message: "费用不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getAllMembers();
  },
  watch: {
    "form.startTime": "calculateDays",
    "form.endTime": "calculateDays",
    // 监听 assignerName 变化并同步到 settleBy
    "form.assigner": function (newValue) {
      const item = this.memberOptions.find(
        (item) => item.memberId === newValue
      );
      if(item!==undefined){
        this.form.settledBy = item.memberName;
      }

    },
    "delegateForm.assigner": function (newValue) {
      const item = this.memberOptions.find(
        (item) => item.memberId === newValue
      );
      if(item!==undefined){
        this.delegateForm.settledBy = item.memberName;
      }
    },
  },
  methods: {
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDetail":
          this.handleDetail(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    // 自定义校验方法：检查结束时间是否大于开始时间
    checkStartTimeIsAfterEndTime(rule, value, callback) {
      const { startTime, endTime } = this.form;
      if (startTime && endTime && new Date(startTime) > new Date(endTime)) {
        callback(new Error("结束时间不能早于发车时间"));
      } else {
        callback(); // 验证通过
      }
    },
    calculateDays() {
      // 清除所有校验错误
      this.$refs.form.clearValidate();
      if (this.form.startTime && this.form.endTime) {
        this.$nextTick(() => {
          // 触发 endTime 校验
          this.$refs.form.validateField("endTime");
        });
        const startTime = new Date(this.form.startTime);
        const endTime = new Date(this.form.endTime);
        endTime.setDate(endTime.getDate() + 1);
        // 计算日期，包含结束日期
        const timeDifference = endTime - startTime;

        //如果日期差距大于0
        if (timeDifference > 0) {
          this.form.days = (timeDifference / (1000 * 3600 * 24)).toFixed(1);
        } else {
          this.form.days = 0;
        }
      } else {
        this.form.days = 0;
      }
    },
    /** 查询所有人员列表 */
    getAllMembers() {
      listAllMembers().then((response) => {
        this.memberOptions = response.data;
      });
    },
    /** 查询行程列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.dateRangeStartTime && "" != this.dateRangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.dateRangeStartTime[0];
        this.queryParams.params["endStartTime"] = this.dateRangeStartTime[1];
      }
      if (null != this.dateRangeEndTime && "" != this.dateRangeEndTime) {
        this.queryParams.params["beginEndTime"] = this.dateRangeEndTime[0];
        this.queryParams.params["endEndTime"] = this.dateRangeEndTime[1];
      }
      listDailyRecord(this.queryParams).then((response) => {
        this.dailyRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelDelegateForm() {
      this.delegateOpen = false;
      this.resetDelegate();
    },
    // 表单重置
    reset() {
      this.form = {
        tripId: undefined,
        assigner: undefined,
        driver: undefined,
        departureLocation: undefined,
        destination: undefined,
        mileage: 1,
        startTime: undefined,
        endTime: undefined,
        days: 0,
        fare: 500,
        settleStatus: "0",
        settledBy: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    resetDelegate() {
      this.delegateForm = {
        tripId: undefined,
        assigner: undefined,
        driver: undefined,
        fare: 1,
        settleStatus: "0",
        remark: undefined,
      };
      this.resetForm("delegateForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRangeStartTime = [];
      this.dateRangeEndTime = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // 提取相关数据
      this.ids = [];
      this.assigners = [];
      this.drivers = [];
      this.totalFare = 0;
      // 遍历选择的行程
      selection.forEach((item) => {
        this.ids.push(item.tripId);
        this.assigners.push(item.assignerName);
        this.drivers.push(item.driver);
        this.totalFare += Number(item.fare) || 0;
      });

      // 设置单选与多选状态
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //查看委托信息或者原始信息
    handleDetail(row) {
      this.detailLoading = true;
      this.detailTitle =
        row.delegateStatus == "1" ? "委派行程详情" : "原始行程详情";
      this.detailOpen = true;
      if (row.delegateStatus == "1") {
        queryDelegateInfo(row.tripId).then((res) => {
          this.detail = res.data;
        });
      }
      if (row.delegateStatus == "2") {
        queryOriginalInfo(row.tripId).then((res) => {
          this.detail = res.data;
          this.detailLoading = false;
        });
      }
    },
    //委派按钮操作
    handleDelegate() {
      if (this.ids.length > 1) {
        this.$modal.msgError("请选择一条行程进行委派");
        return;
      }
      this.resetDelegate();
      this.delegateOpen = true;
      this.delegateForm.assigner = this.drivers[0];
    },
    submitDelegateForm() {
      this.$refs["delegateForm"].validate((valid) => {
        if (valid) {
          this.delegateButtonLoading = true;
          this.delegateForm.tripId = this.ids[0];
          delegateTripRecord(this.delegateForm)
            .then((res) => {
              this.$modal.msgSuccess("委派成功");
              this.delegateOpen = false;
              this.getList();
            })
            .finally(() => {
              this.delegateButtonLoading = false;
            });
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加行程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tripId = row.tripId || this.ids;
      getDailyRecord(tripId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改行程";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.tripId != null) {
            updateDailyRecord(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addDailyRecord(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tripIds = row.tripId || this.ids;
      this.$modal
        .confirm('是否确认删除行程编号为"' + tripIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delDailyRecord(tripIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 结账按钮操作 */
    handleSettle(row) {
      const tripIds = row.tripId || this.ids;
      if (tripIds.length < 0) {
        this.$modal.msgError("请至少选择一条进行结账");
      }
      const assigners = row.assignerName || this.assigners;
      const totalFare = row.fare || this.totalFare;
      const h = this.$createElement;
      const message = h("div", [
        h("p", '是否对指派人为 "' + assigners + '" 的行程进行结账？'),
        h("i", "请核对总费用："),
        h("i", { style: "color: #f16e6e;font-weight: bold" }, totalFare + "元"),
      ]);
      this.$confirm(message, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          return settleDailyRecord(tripIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("结账成功");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消结账",
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "trip/dailyRecord/export",
        {
          ...this.queryParams,
        },
        `行程记录_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
